﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using ZeroBugBounce.Missive.Locks;

namespace ZeroBugBounce.Missive
{
	public partial class Messenger
	{
		public readonly Topic DefaultTopic;
		public readonly Topic AllTopics;

		Dictionary<int, Topic> TopicCache = new Dictionary<int, Topic>();
		ILock TopicCacheLock = new NoSpinHybridLock();

		public Topic ParseTopic(object topic)
		{
			string textTopic = topic.ToString().ToLowerInvariant();

			TopicCacheLock.Enter();
			if (TopicCache.ContainsKey(textTopic.GetHashCode()))
			{
				var cachedTopic = TopicCache[textTopic.GetHashCode()];
				TopicCacheLock.Leave();
				return cachedTopic;
			}
			TopicCacheLock.Leave();

			Topic instance = new Topic();

			instance.parts = textTopic.Split('.').Select(part => part.GetHashCode()).ToArray();
			instance.fullTopic = textTopic;
			instance.hash = instance.fullTopic.GetHashCode();

			TopicCacheLock.Enter();
			TopicCache[textTopic.GetHashCode()] = instance;
			TopicCacheLock.Leave();

			return instance;
		}

		public Topic[] QueryKnownTopics()
		{
			Topic[] topics;
			TopicCacheLock.Enter();
			topics = new Topic[TopicCache.Values.Count];
			TopicCache.Values.CopyTo(topics, 0);
			TopicCacheLock.Leave();
			return topics;
		}
	}
}
